package net.download;

import java.io.IOException;

import util.Parameters;

import data.dao.DAOFactory;
import data.model.Data;

import net.connection.Connection;
import net.connection.ConnectionManagerFactory;
import net.peer.Peer;
import net.protocol.ProtocolFactory;

public class Download implements Runnable{
	private Connection connection;
	private Peer peer;
	
	public Download(Connection connection, Peer peer) {
		this.connection = connection;
		this.peer = peer;
	}

	@Override
	public void run() {
		try {
			Data data = (Data)ProtocolFactory.getProtocol().recieveData(connection.getSocket().getInputStream());
			

			switch(Parameters.MODE){
				case Parameters.RECOVER:
					DAOFactory.getRecoveredDAO().saveData("recovered/data.txt", data, true);
				break;
				
				case Parameters.BACKUP:
					DAOFactory.getRepositoryDAO().saveData("repository/data.txt", data, false);
				break;
				
				default:
					throw new RuntimeException("Mais mais mais c'est pas un mode valide");
			}
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			ConnectionManagerFactory.getManager().closeConnection(peer,connection);
		}
	}
	
	public boolean isConnected(){
		return connection != null;
	}

}
